package com.moyv.schoolbbs.database;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.Date;

public class DatabaseUtil {
    private String name;
    private SQLiteDatabase sqLiteOpenHelper;

    public DatabaseUtil(Context context, String name) {
        this.name = name;
        try {
            MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(context, name, null, context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode);
            sqLiteOpenHelper = myDatabaseHelper.getReadableDatabase();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean updateDialog(String account, String count) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("unreadCount", count);
        sqLiteOpenHelper.update("Conversation", contentValues, "name=?", new String[]{account});
        return true;
    }

    public boolean insertDialog(String account, String title, String users, String unreadCount) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", account);
        contentValues.put("title", title);
        contentValues.put("users", users);
        contentValues.put("unreadCount", unreadCount);
        sqLiteOpenHelper.insert("Conversation", null, contentValues);
        return true;
    }

    public boolean insertMessage(String account, String username, String mes, Date date, boolean isChat) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", account);
        contentValues.put("username", username);
        contentValues.put("mes", mes);
        contentValues.put("ischat", isChat ? 0 : 1);
        contentValues.put("time", date.toString());
        sqLiteOpenHelper.insert("Message", null, contentValues);
        return true;
    }

    public Cursor getAll(String table) {
        Cursor cursor = sqLiteOpenHelper.query(table, null, null, null, null, null, null);
        return cursor;
    }

    public Cursor getMessageALL(String name) {
        Cursor cursor = sqLiteOpenHelper.query("Message", null, "name=?", new String[]{name}, null, null, null);
        return cursor;
    }

    public Cursor getMessageLimit(String name, String from, String len) {
        Cursor cursor = sqLiteOpenHelper.query("Message", null, "name=?", new String[]{name}, null, null, "id desc", from + "," + len);
        return cursor;
    }

    public Cursor getMessageLast(String name) {
        Cursor cursor = sqLiteOpenHelper.query("Message", null, "name=?", new String[]{name}, null, null, "id desc", "1");
        return cursor;
    }

    public SQLiteDatabase getSqLiteOpenHelper() {
        return sqLiteOpenHelper;
    }
}
